//保存表格的实例对象
var sx = null;

//封装方法重载表格
function sxTable(){
    sx.reload()
}

layui.use(['table','form'], function(){
    var table = layui.table;
    var form = layui.form;

    //提交筛选查询
    form.on('submit(*)',function (data){
        var data = data.field;
        sx.reload({
            url:'/getPrintRecordByStuName',
            where:{
                studentName:data.studentName
            }
        },true)
        return false
    })

    //提交数据重置为空
    form.on('submit(cz)',function (data){

        $("[name=studentName]").val(undefined)

        sx.reload({
            url:'/getPrintRecord',
        },true)
        return false
    })

    //第一个实例
    sx = table.render({
        elem: '#demo'
        ,url: '/getPrintRecord' //数据接口
        ,page:{
            layout:['count','prev','page','next','limit'],
            groups:5,
            limit:10,
            limits:[3,5,10]
        }
        , height:350
        ,cols: [
            [
                {checkbox: true},
                {field: 'recordId', title: '打印编号', width:200,align: 'center'},
                {field: 'studentId', title: '学号', width:215,align: 'center'},
                {field: 'documentId', title: '订单编号', width:265,align: 'center'},
                {field: 'recordRemark', title: '打印结果', width:220,align: 'center',templet:function (d){
                        if (d.recordRemark == 0){
                            return '打印成功';
                        }else {
                            return '打印失败';
                        }
                    }},
                {title: '操作',templet:'#tooldemo',width: 200,align: 'center'}
            ]
        ],
        defaultToolbar: ['filter'],
        toolbar:'#toolbardemo',
        parseData:function (res){
            return{
                "code":res.state,
                "msg":res.msg,
                "count":res.total,
                "data":res.data
            }
        }
    })


        //tool 监听工具条
        table.on('tool(stuTable)',function(obj){
            //发送ajax获取学生和订单信息
            $.ajax({
                type:'post',
                url:'/getPrint',
                data:obj.data,
                dataType: 'json',
                success:function (res){
                    if (res.state == '200'){
                        console.log(res.data[0].document_id)
                        layer.msg('请求成功')
                        var prints = {
                            payee : JSON.parse(sessionStorage.getItem("user")).userName,
                            documentId:res.data[0].document_id,
                            project:res.data,
                            actualPrice:0
                        }
                        $.each(res.data,function (i){
                            prints.actualPrice+=res.data[i].have_fees
                        })
                        console.log("pr",prints)
                        printSelect(prints)
                    }else {
                        layer.msg('请求发送失败')
                    }
                }
            })
        })

})

//自定义打印页面
function printSelect(Document) {
    console.log(Document)
    //用于包含内容
    var v = document.createElement("div");
    //页面头部，导入css  ，media="print"表示打印时使用该样式
    var f = ["<head>", "<style>",
        "th{height: 30px;font-weight:500 ;}",
        "h1{font-weight:500 ;}",
        "</style>", "</head>"
    ].join("");
    var contentHtml = "";
    var template = ""
    var head =
        "<div style= 'width: 80%; margin: 0 auto;'>" +
        "<div style= 'overflow: hidden; box-sizing:border-box; '>" +
        "<h1 style= 'width: 200px; margin: 0 auto; padding-top: 20px;'>进思学生单据</h1>" +
        "<div style= 'margin-bottom: 5px; margin-top: 5px;width: 200px; margin-left: 100px; float: left' > " +
        "单据号：" + Document.documentId +
        "</div>"+
        "<div style= 'margin-bottom: 5px; margin-top: 5px;width: 200px; margin-right: 100px; float: right' > " +
        "市场部：" + Document.project[0].marketing_name +
        "</div>"+
        "</div>"+
        "<table border='1' cellSpacing='0' style='width: 100%;'>" +
        "<tr>" +
        "<th>学号</th>" +
        "<th>"+ Document.project[0].student_id +"</th>" +
        "<th>姓名</th>" +
        "<th>"+ Document.project[0].student_name +"</th>" +
        "<th>班级</th>" +
        "<th>"+ Document.project[0].classes_name +"</th>" +
        "</tr>" +
        "<tr>"+
        "<th>学期</th>"+
        "<th>"+ Document.project[0].student_school_term +"</th>"+
        "<th colSpan='2''>入学时间</th>"+
        "<th colSpan='2'>"+ Document.project[0].student_create_date +"</th>"+
        "</tr>"+
        "<tr>"+
        "<th colspan='2'>收费项目</th>"+
        "<th>收费标准</th>"+
        "<th>收费金额</th>"+
        "<th>单据减免</th>"+
        "<th>单据年份</th>"+
        "</tr>"
    var body = "";
    for (var i = 0 ; i < Document.project.length ; i++){
        body +=
            "<tr>"+
            "<th colspan='2'>"+ Document.project[i].project_name +"</th>"+
            "<th>"+ Document.project[i].amount_receivable +".00</th>"+
            "<th>"+ Document.project[i].have_fees +".00</th>"+
            "<th>"+ Document.project[i].preferential_price +"</th>"+
            "<th>"+ Document.project[i].generated_time.slice(0,4) +"</th>"+
            "</tr>"
    }
    var food =
        "<tr>"+
        "<th colspan='2'></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "</tr>"+
        "<tr>"+
        "<th colspan='2'></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "</tr>"+
        "<tr>"+
        "<th style='border-right:hidden;'>行政事业性收费小计：</th>"+
        "<th colSpan='4' style='border-left:hidden; border-right: hidden; '></th>"+
        "<th style='border-left:hidden ;'>￥"+ Document.actualPrice +".00</th>"+
        "</tr>"+
        "<tr>"+
        "<th>合计金额（大写）</th>"+
        "<th style='border-right: hidden;'>"+ changeNumMoneyToChinese(Document.actualPrice) +"</th>"+
        "<th colSpan='3' style='border-left: hidden; border-right: hidden;'></th>"+
        "<th style='border-left: hidden;'>￥"+Document.actualPrice +".00</th>"+
        "</tr>"+
        "</table>"+

        "<div style='margin-left: 600px; width: 200px; padding-top:5px ;'>收款人："+ Document.payee +"</div>"+
        "</div>"

    template += head;
    template += body;
    template += food;
    contentHtml += template;
    //contentHtml为已拼凑好的内容
    $(v).append(contentHtml)


    $.ajax({
        type:"POST",
        url:"/htmlToPdf",
        dataType:"json",
        data:{"printHtml":printHtml,"template":template},
        success:function(data){
            console.log(data);
            print2();
        }
    });

    function print2(){
        //添加ifrme标签
        $("#addiframe").html("<iframe style='display:none' name = 'template' id='printIframe' src='/01.pdf'>");
        //打印预览
        $("#printIframe")[0].contentWindow.print();
    }

    // //新建窗口
    // var h = window.open("打印窗口", "_blank");
    // //写入拼凑内容
    // h.document.write(f + $(v).prop("outerHTML"));
    //
    //
    // //调用打印
    // h.print();
    // //关闭页面
    // h.close();

}


//数子转换大写格式
function changeNumMoneyToChinese(money) {
    var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
    var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
    var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
    var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
    var cnInteger = "整"; //整数金额时后面跟的字符
    var cnIntLast = "元"; //整型完以后的单位
    var maxNum = 999999999999999.9999; //最大处理的数字
    var IntegerNum; //金额整数部分
    var DecimalNum; //金额小数部分
    var ChineseStr = ""; //输出的中文金额字符串
    var parts; //分离金额后用的数组，预定义
    var Symbol = ""; //正负值标记
    if (money == "") {
        return "";
    }

    money = parseFloat(money);
    if (money >= maxNum) {
        alert('超出最大处理数字');
        return "";
    }
    if (money == 0) {
        ChineseStr = cnNums[0] + cnIntLast + cnInteger;
        return ChineseStr;
    }
    if (money < 0) {
        money = -money;
        Symbol = "负 ";
    }
    money = money.toString(); //转换为字符串
    if (money.indexOf(".") == -1) {
        IntegerNum = money;
        DecimalNum = '';
    } else {
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 4);
    }
    if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
        var zeroCount = 0;
        var IntLen = IntegerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = IntegerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; //归零
                ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                ChineseStr += cnIntUnits[q];
            }
        }
        ChineseStr += cnIntLast;
        //整型部分处理完毕
    }
    if (DecimalNum != '') { //小数部分
        var decLen = DecimalNum.length;
        for (var i = 0; i < decLen; i++) {
            var n = DecimalNum.substr(i, 1);
            if (n != '0') {
                ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (ChineseStr == '') {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (DecimalNum == '') {
        ChineseStr += cnInteger;
    }
    ChineseStr = Symbol + ChineseStr;

    return ChineseStr;
}